package com.cangxuan.manage.service.impl;

import com.cangxuan.manage.dao.IAdminDao;
import com.cangxuan.manage.entity.Admin;
import com.cangxuan.manage.exception.ServiceException;
import com.cangxuan.manage.service.IAdminService;
import com.cangxuan.manage.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class AdminServiceImpl implements IAdminService {

    IAdminDao adminDao;

    @Autowired
    public void setAdminDao(IAdminDao adminDao) {
        this.adminDao = adminDao;
    }

    RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public void setredisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public String login(Admin admin) {
        if (adminDao.selectCount(admin.getUsername(), SecurityUtils.md5(admin.getUsername() + admin.getPassword())) == 0) {
            throw new ServiceException(401, "用户名或者密码错误");
        }
        //程序走到这儿，说明登录成功
        String sign = UUID.randomUUID().toString();     //返回给前端的一个凭证
        //以凭证为键，保存对应的登录用户对象
        redisTemplate.opsForValue().set("admin-" + sign, admin.getUsername(), 30, TimeUnit.MINUTES);
        return sign;
    }


    @Override
    public boolean changePassword(String oldPwd, String newPwd) {
        if (adminDao.getPassword().equals(oldPwd)) {
            return adminDao.changePassword(newPwd) > 0;
        }
        else {return false;}
    }
}


